package com.yiyuzi.admin.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiyuzi.admin.common.AdminInterceptorAdapter;
import com.yiyuzi.admin.common.constant.ResponseCodeEnum;
import com.yiyuzi.admin.common.domain.PageResultDTO;
import com.yiyuzi.admin.common.utils.ConvertUtils;
import com.yiyuzi.admin.common.utils.UserUtils;
import com.yiyuzi.admin.token.domain.TokenEntity;
import com.yiyuzi.admin.token.service.TokenService;
import com.yiyuzi.admin.user.UserDao;
import com.yiyuzi.admin.user.domain.dto.*;
import com.yiyuzi.admin.user.domain.entity.UserEntity;
import com.yiyuzi.admin.user.domain.entity.UserRoleEntity;
import com.yiyuzi.admin.user.service.UserRoleService;
import com.yiyuzi.admin.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yiyuzi
 * @date 2021/5/8 9:09
 */

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private TokenService tokenService;

    @Override
    public String login(UserLoginDTO userLoginDTO) {
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>()
                .eq(userLoginDTO.getLoginName() != null, "login_name", userLoginDTO.getLoginName())
                .eq(userLoginDTO.getLoginPwd() != null, "login_pwd", UserUtils.getMD5Str(userLoginDTO.getLoginPwd())));
        if (userEntity == null){
            return null;
        }
        return tokenService.createToken(userEntity.getId());
    }

    @Override
    public boolean logout(String token) {
        if (!tokenService.isValid(token))
            return false;
        return tokenService.remove(new QueryWrapper<TokenEntity>().eq("token", token));
    }

    @Override
    public boolean save(UserAddDTO addDTO) {
        addDTO.setLoginPwd(UserUtils.getMD5Str(addDTO.getLoginPwd()));
        return this.save(ConvertUtils.copy(addDTO, UserEntity.class));
    }

    @Override
    public boolean update(UserUpdateDTO updateDTO) {
        if (updateDTO.getLoginPwd() != null)
            updateDTO.setLoginPwd(UserUtils.getMD5Str(updateDTO.getLoginPwd()));
        return this.updateById(ConvertUtils.copy(updateDTO, UserEntity.class));
    }

    // 存在返回true
    @Override
    public boolean isUserNameExist(String userName) {
        return this.getOne(new QueryWrapper<UserEntity>().eq("login_name", userName)) != null;
    }

    @Override
    public PageResultDTO<UserDTO> findPage(UserQueryDTO userQueryDTO) {
        LOGGER.info("获取全部用户");
        List<UserEntity> list = this.list(new QueryWrapper<UserEntity>()
                .eq(userQueryDTO.getId() != null,"id", userQueryDTO.getId())
                .like(userQueryDTO.getLoginName() != null, "login_name", userQueryDTO.getLoginName())
                .like(userQueryDTO.getActualName() != null, "actual_name", userQueryDTO.getActualName()));
        return ConvertUtils.convertPageResult(list, UserDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        if (!this.removeById(id)){
            throw new RuntimeException(ResponseCodeEnum.FAIL.getDesc());
        }
        this.deleteUserRelation(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteList(List<Long> list) {
        for(Long id: list) {
            this.deleteById(id);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    void deleteUserRelation(Long id){
        List<UserRoleEntity> userRoleEntityList = userRoleService.list(new QueryWrapper<UserRoleEntity>()
                .eq(id != null,"user_id", id));
        for(UserRoleEntity entity : userRoleEntityList){
            if (!userRoleService.removeById(entity.getId())){
                throw new RuntimeException(ResponseCodeEnum.FAIL.getDesc());
            }
        }
    }
}
